<template>
  <div class="response-detail" ref="detailRef" :class="{ 'is-left': isLeft }">
    <Modal
      v-if="props.visible"
      :maskClosable="false"
      @closeModal="close"
      @cancel="close"
    >
      <template #modalContent>
        <div class="modal-item" :class="{ 'half-screen': isHalfScreen }">
          <header class="header">
            <p class="title">
              {{ isCompareTeaching ? '请选择对比学生' : '学生作答详情' }}
            </p>
            <p>
              <span
                class="half-screen-down icon"
                :class="{
                  'half-screen-up': isHalfScreen,
                  disabled: props.outerHalf
                }"
                @click="halfScreen('icon')"
              ></span>
              <span class="close icon" @click="close"></span>
            </p>
          </header>
          <main class="main" :class="{ 'half-screen': isHalfScreen }">
            <!-- 选择题 -->
            <template v-if="studentList.list.length">
              <div
                v-for="(option, index) in studentList.list"
                :key="index"
                class="option"
              >
                <p class="option__summary">
                  <span class="ratio">
                    <template v-if="isObject">
                      <img
                        class="tip-icon"
                        v-if="option.statistics_type !== 6"
                        :src="option.key"
                      />
                      <div class="text" v-else>{{ option.text }}</div>
                    </template>
                    <span v-else>{{ option.key }}</span>
                    <a-progress
                      class="progress"
                      :strokeColor="getColor(option)"
                      :percent="getPercent(option.total)"
                      :format="formatPercent"
                      status="normal"
                    ></a-progress
                  ></span>
                  <span class="num"
                    ><span>{{ option.total || 0 }} 人</span>
                    <span
                      v-show="option.total > 0"
                      :class="option.isOpened ? 'opened' : 'icon'"
                      @click="showStudents(index)"
                    ></span
                  ></span>
                </p>
                <div
                  class="student-list"
                  v-if="option.list.length && option.isOpened"
                >
                  <button
                    v-for="item in option.list"
                    :key="item.student_id"
                    class="student-btn"
                    @click="showDetail(item)"
                    :class="{ active: selectedList.includes(item.student_id) }"
                  >
                    <label
                      class="excellent"
                      v-if="item.question_sign === 1"
                    ></label>
                    <label
                      v-if="item.question_sign === 2"
                      class="typical"
                    ></label>
                    {{
                      commentStore.isShowTypical && item.question_sign === 2
                        ? '***'
                        : item.student_name
                    }}
                  </button>
                </div>
              </div>
            </template>
          </main>
          <footer v-if="isObject" class="footer">
            <!-- <span v-if="isCompareTeaching">
              <button
                class="btn cancel-btn"
                @click="cancelCompareReview"
              >
                取消
              </button>
              <button
                class="btn confirm-btn"
                :class="{ disabled: selectedList.length === 0 }"
                @click="goAssessment"
              >
                对比讲评({{ selectedList.length }}人)
              </button>
            </span>
            <button
              class="btn confirm-btn"
              v-else
              @click="compareReview"
            >
              选择学生对比讲评
            </button> -->
          </footer>
          <footer v-else>
            <p class="tip">*客观题暂不支持查看学生详情和对比讲评</p>
          </footer>
        </div>
      </template>
    </Modal>
  </div>
</template>
<script setup>
import Modal from './Modal.vue'
import { ref, reactive, watch, computed, watchEffect, onMounted } from 'vue'
import { getType6Text, rankMap } from '@/views/assignment/util'
import { getResponseStatistics } from '@/apis/assignment'
import { useComment } from '@/stores/comment'
import { useAuthStore } from '@/stores/auth-store'
import { useRouter, useRoute } from 'vue-router'
import $bus from '@/utils/tools/bus'
import { ElMessage } from 'element-plus'
const route = useRoute()
const router = useRouter()
const { userInfo } = useAuthStore()
const commentStore = useComment()
const isCompareTeaching = ref(false)
const detailRef = ref(null)
const isHalfScreen = ref(false)
const modalHeight = ref('650px')
const isLeft = ref(false)
const props = defineProps({
  visible: {
    default: false,
    type: Boolean
  },
  rightAnswer: {
    default: '',
    type: String
  },
  outerHalf: {
    default: false,
    type: Boolean
  }
})

const singleChoiceType = [1, 55]
const multiChoiceType = [2, 80]
const judgeType = [36, 57]
const isObject = computed(() => {
  const list = [...singleChoiceType, ...multiChoiceType, ...judgeType]
  return !list.includes(commentStore.currentQuestion.question_detail.type)
})

const objectEnum = [
  {
    desc: '[85%,100%]',
    type: 'excellent'
  },
  {
    desc: '[70%,85%)',
    type: 'good'
  },
  {
    desc: '[60%,70%)',
    type: 'qualified'
  },
  {
    desc: '[0%,60%)',
    type: 'no_qualified'
  }
]

// TODO：缺参数
const getPercent = num => {
  const total = studentList.list.reduce((a, b) => {
    return a + b.list.length
  }, 0)
  return parseFloat(((num / total) * 100).toFixed(1))
}

const getColor = content => {
  // 选择题需要匹配正确选项
  if (!isObject.value) {
    if (content.isCorrect) {
      return 'rgba(0, 189, 141, 1)'
    }
    return 'rgba(255, 90, 80, 1)'
  }
  return 'rgba(0, 189, 141, 1)'
}

const studentList = reactive({
  list: [],
  excellent: {
    isOpened: false,
    list: []
  }
})

const emits = defineEmits(['close-dialog'])
const selectedList = ref([])
watch(
  () => props.visible,
  val => {
    if (val && props.outerHalf) {
      isHalfScreen.value = false
      halfScreen()
    }
  }
)

const getDetail = async () => {
  const params = {
    task_id: route.query.task_id,
    class_id: route.query.class_id,
    question_id: commentStore.currentQuestion.question_id,
    item_type: 1
  }
  const { data } = await getResponseStatistics(params)
  const result = data.result || {}
  const keys = Object.keys(result)
  studentList.list = keys.map(key => {
    const res = {
      key: key,
      list: result[key].list || [],
      isCorrect: false,
      isOpened: false,
      total: result[key].total || 0,
      statistics_type: data.statistics_type
    }
    switch (data.statistics_type) {
      case 1:
      case 2:
      case 3:
        res.isCorrect = key === props.rightAnswer
        res.key = `【${key}】`
        break
      case 4:
        res.key = key === 'correct' ? '【对/T】' : '【错/F】'
        res.isCorrect =
          (key === 'correct' && Number(props.rightAnswer) == 0) ||
          (key === 'wrong' && Number(props.rightAnswer) == 1)
        break
      case 5:
        res.key = rankMap[key]
        res.isCorrect = true
        res.tip = key
        break
      case 6:
        res.isCorrect = true
        res.text = getType6Text(key, data.set_total_score)
    }
    return res
  })
  // 按顺序处理整合数据
  if (data.statistics_type === 5) {
    const res = []
    const list = ['all_correct', 'part_correct', 'incorrect', 'await_grade']
    for (let index = 0; index < list.length; index++) {
      const current = list[index]
      const e = studentList.list.find(item => item.tip === current)
      res.push(e)
    }
    studentList.list = res
  }
}

watchEffect(async () => {
  if (commentStore.currentQuestion.question_id && props.visible) {
    studentList.list = []
    getDetail()
  }
})

const formatPercent = num => {
  return num + '%'
}

const showDetail = content => {
  if (isCompareTeaching.value) {
    if (selectedList.value.includes(content.student_id)) {
      const index = selectedList.value.findIndex(
        item => item === content.student_id
      )
      selectedList.value.splice(index, 1)
    } else {
      selectedList.value.push(content.student_id)
    }
  } else {
    if (!isObject.value) return
    selectedList.value.splice(0, 1, content.student_id)
    commentStore.setStudentIds(selectedList.value)
    router.push({
      path: '/comment/studentResponse',
      query: {
        ...route.query,
        question_id: commentStore.currentQuestion.question_id
      }
    })
  }
}

const halfScreen = source => {
  if (props.outerHalf && source) {
    return
  }
  isHalfScreen.value = !isHalfScreen.value
  if (isHalfScreen.value) {
    modalHeight.value = '430px'
  } else {
    modalHeight.value = '650px'
  }
}

const close = () => {
  selectedList.value = []
  emits('close-dialog')
}
const cancelCompareReview = () => {
  isCompareTeaching.value = false
  selectedList.value = []
}

const compareReview = () => {
  isCompareTeaching.value = false
  // isCompareTeaching.value = true
  // selectedList.value = []
}

const showStudents = index => {
  studentList.list[index].isOpened = !studentList.list[index].isOpened
}

const goAssessment = () => {
  if (selectedList.value.length === 0) {
    ElMessage.warning('至少选择一个学生！')
    return
  }
  commentStore.setStudentIds(selectedList.value)
  router.push({
    path: '/homeworkAssessment/studentCompare'
  })
}

onMounted(() => {
  const flag = sessionStorage.getItem('is-left')
  isLeft.value = flag ? JSON.parse(flag) : false
  $bus.on('change-position', () => {
    isLeft.value = !isLeft.value
  })
})

defineExpose({
  isHalfScreen,
  halfScreen
})
</script>
<style lang="less" scoped>
.response-detail {
  z-index: 100;
  position: absolute;
  right: 0;
  bottom: 60px;
  height: fit-content;

  &.is-left {
    left: 0;
  }
  :deep(.mask) {
    width: fit-content;
    position: unset;
    height: fit-content;
  }
  :deep(.modal) {
    padding: 0 !important;
    * {
      color: rgba(4, 11, 26, 0.75);
    }
    .modal-top {
      display: none !important;
    }

    .modal-btn {
      display: none !important;
    }

    .modal-content {
      padding: 0 24px !important;
    }
  }
  .modal-item {
    height: 650px;
    width: 313px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    &.half-screen {
      height: 430px;
    }

    .header {
      display: flex;
      justify-content: space-between;
      height: 72px;
      align-items: center;

      .title {
        font-weight: 700;
        font-size: 18px;
      }

      .icon {
        width: 24px;
        height: 24px;
        display: inline-block;
        cursor: pointer;
        margin-left: 10px;
      }
      .half-screen-down {
        background: url('@/assets/images/comment/response-half-screen.png')
          no-repeat center/cover;

        &.half-screen-up {
          background: url('@/assets/images/comment/half-screen-up.png')
            no-repeat center/cover;
        }

        &.disabled {
          cursor: not-allowed;
          opacity: 0.4;
        }
      }

      .close {
        background: url('@/assets/images/comment/response-close.png') no-repeat
          center/cover;
      }
    }

    .main {
      flex: 1;
      overflow-y: auto;

      &.half-screen {
        height: 280px;
      }
      &::-webkit-scrollbar {
        width: 5px !important;
        height: 20px !important;
      }
      &::-webkit-scrollbar-thumb {
        border-radius: 5px !important;
      }
      &::-webkit-scrollbar-track {
        border-radius: 5px !important;
        background: #fffefe00 !important;
      }

      .option {
        &__summary {
          display: flex;
          align-items: center;
          gap: 24px;
          margin-bottom: 16px;

          .ratio {
            flex: 1;
            display: inline-flex;
            align-items: center;

            .tip-icon {
              width: 30px;
              height: 30px;
            }

            .desc {
              display: inline-block;
              min-width: 100px;
            }

            .progress {
              flex: 1;
            }
            .text {
              width: 60px;
              text-align: left;
            }
          }

          .num {
            width: 68px;
            display: inline-flex;
            justify-content: space-between;
            align-items: center;
          }

          .icon {
            cursor: pointer;
            display: inline-block;
            width: 20px;
            height: 20px;
            background: url('@/assets/images/comment/down-close.png') no-repeat
              center/cover;
          }

          .opened {
            cursor: pointer;
            display: inline-block;
            width: 20px;
            height: 20px;
            background: url('@/assets/images/comment/up-open.png') no-repeat
              center/cover;
          }
        }
      }
      .student-list {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-bottom: 16px;
      }

      .student-btn {
        text-overflow: ellipsis;
        white-space: nowrap;
        overflow: hidden;
        display: inline-block;
        text-align: center;
        vertical-align: middle;
        border-radius: 8px;
        height: 30px;
        width: 92px;
        font-size: 14px;
        border: 1px solid rgba(242, 243, 244, 1);
        background: #fff;
        color: rgba(4, 11, 26, 0.5);
        cursor: pointer;

        label {
          width: 18px;
          height: 18px;
          display: inline-block;
          vertical-align: sub;
        }

        .excellent {
          background: url('@/assets/images/comment/excellent-small.svg')
            no-repeat center/cover;
        }

        .typical {
          background: url('@/assets/images/comment/typical-small.svg') no-repeat
            center/cover;
        }
      }

      .active {
        border: 1px solid rgba(0, 189, 141, 1);
        background: rgba(230, 248, 244, 1);
        color: rgba(0, 189, 141, 1);
      }
    }

    .footer {
      text-align: right;
      padding: 24px 0;
      height: fit-content;
      .btn {
        border-radius: 8px;
        padding: 8px 16px;
        font-size: 14px;
        width: fit-content;
        height: fit-content;
      }

      .confirm-btn {
        border: 1px solid;
        color: #fff;
        background: rgba(0, 189, 141, 1);
        border: 1px solid rgba(0, 189, 141, 1);
        box-shadow: unset;

        &.disabled,
        &:disabled {
          opacity: 0.4;
          cursor: not-allowed;
        }
      }

      .cancel-btn {
        background: #fff;
        border: 1px solid rgba(217, 218, 221, 1);
        margin-right: 10px;
      }
    }

    .tip {
      display: flex;
      align-items: center;
      padding: 24px 0;
      color: #040b1a;
      opacity: 0.3;
    }
  }
}
</style>
